package net.easyjava.framework.web.adapter;

import com.alibaba.fastjson.JSONObject;
import net.easyjava.framework.BaseConstants;
import net.easyjava.framework.log.LogConstants;
import net.easyjava.framework.utils.EnvironmentProperties;
import net.easyjava.tools.http.request.RequestTools;
import net.easyjava.tools.lang.StringTools;
import net.easyjava.tools.model.ModelBean;
import net.easyjava.tools.security.SignTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;

/**
 * Created by wxnacy on 16/7/1.
 */
public class ControllerSecurityAdapter extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    protected static final String API_SIGN_KEY = "a2dc8a390e92ab87678a5bf922fbd5dd";

    public static final String CONTENT_TYPE_JSON = "application/json; charset=UTF-8";
    public static final String CONTENT_TYPE_TEXT = "text/html;charset=UTF-8";
    public static final String ADAPTER_NO_SECURITY_URL = "adapter.no.security.url";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String url = RequestTools.getRealUrl(request);
        String relativeUrl = RequestTools.getRelativeUrl(request);

        //检查不需要加密的接口
        String urls = EnvironmentProperties.getInstance().getProperty(ADAPTER_NO_SECURITY_URL);
        if(!StringTools.isEmpty(urls)){
            String[] urlArr = urls.split(",");
            int index = Arrays.binarySearch(urlArr,relativeUrl);
            if(index>-1){
                return true;
            }
        }
        String createSign = SignTools.createSign(request, API_SIGN_KEY);
        //获取sign
        String sign = RequestTools.getParam(request, "sign", "default");
        ModelBean modelBean = new ModelBean();
        if(sign.equalsIgnoreCase(createSign)){
           return true;
        }
        modelBean = new ModelBean(BaseConstants.ERROR_NO_PERMISSION);


        /**
         * 返回结果
         */

        Map<String,String[]> params = request.getParameterMap();
        PrintWriter out = null;
        try {
            logger.info(LogConstants.API_ADAPTER_TIME_SUM, new Object[]{url,modelBean.getMessage()});
            if(params.containsKey("callback")){
                response.setContentType(CONTENT_TYPE_TEXT);
                out = response.getWriter();
                out.write(new String(params.get("callback")[0] + "("));
                out.write(JSONObject.toJSONString(modelBean));
                out.write(new String(");"));
            }else {
                response.setContentType(CONTENT_TYPE_JSON);
                out = response.getWriter();
                out.write(JSONObject.toJSONString(modelBean));
            }
            out.flush();
            out.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e.fillInStackTrace());
        }
        return false;
    }


}
